<?php

class Service_menus extends MY_Service
{
    public function __construct()
    {
        parent::__construct();
        $this->load->driver('cache');
        $this->load->model('Model_menus');
    }

    public function getList($type = 'left')
    {
        $mcKey = $type . '_menus';
        $result = $this->cache->memcached->get($mcKey);
        if (!empty($result)) {
            $this->_isCurrent($result);
            return $result;
        }

        $cond = [
            'status' => 0,
            'pid' => 0,
            'type' => $type
        ];
        $result = $this->Model_menus->getList(false, $cond);
        foreach ($result as &$row) {
            if ($row['has_child']) {
                $cond = [
                    'status' => 0,
                    'pid' => $row['id']
                ];
                $subList = $this->Model_menus->getList(false, $cond);
                $row['childs'] = $subList;
            }
        }
        $this->cache->memcached->save($mcKey, $result, 86400);
        $this->_isCurrent($result);
        return $result;
    }

    /**
     * 判断是否当前菜单
     * @param $result
     */
    private function _isCurrent(&$result)
    {
        // 判断是否当前菜单
        $uri = $_SERVER['REQUEST_URI'];
        $uri = urldecode($uri);
        foreach ($result as &$menu) {
            $menu['is_current'] = $uri == $menu['url'];
        }
    }

}
